package tablasSql;

import callable.AIConsulta;
import callable.Existe;
import callable.HacerConsulta;
import callable.HacerConsulta2;
import callable.Tiempo;
import gestion.Principal;
import java.awt.Cursor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import otros.Configuracion;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author FERRETERIA
 */
public class ConsultaBD {
    
    private Connection conexion = null;
    private final static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ConsultaBD.class);
    
    private String url = Configuracion.getInstance().getProperty(Configuracion.DATABASE_SERVER);    //"localhost";
    private String bd = Configuracion.getInstance().getProperty(Configuracion.DATABASE_CATALOG);    //"gestion";
    private String us = Configuracion.getInstance().getProperty(Configuracion.DATABASE_USER);       //"root";
    private String psw = Configuracion.getInstance().getProperty(Configuracion.DATABASE_PSWD);      //"mysql82";
         
    
    public void consola(String text, int tipo) {
        switch(tipo) {
            case 1:
                log.warn(text);
                break;
            case 2:
                log.error(text);
                break;
            default:
                log.info(text);
                break;
        }
    }
    
    public static void cursorEspera(JInternalFrame f) {
        if (f != null)
            f.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        else
            Principal.getPanel().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    }
    
    public static void cursorNormal (JInternalFrame f) {
        if(f != null)
            f.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        else
            Principal.getPanel().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
    
    public ConsultaBD() {
        try {
            Class.forName("com.mysql.jdbc.Driver");  
            conexion = DriverManager.getConnection ("jdbc:mysql://" + url + "/" + bd,us,psw);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getPanel(), "No se ha podido conectar a la base de datos", 
                                            "ERROR", JOptionPane.ERROR_MESSAGE);
            consola(e.toString(),2);
        }
    }
    
    public boolean existe(String sql) {
        if (conexion != null) {
            Existe call = new Existe(conexion, sql);

            FutureTask<Boolean> tarea = new FutureTask<Boolean>(call);

            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.execute(tarea);
            try {
                while(!tarea.isDone())
                    cursorEspera(null);
                if(tarea.isDone()){
                   boolean valor = tarea.get();
                   executor.shutdown();
                   cursorNormal(null);
                   return valor;
                }
                cursorEspera(null);
            }catch(Exception e) {
                consola("Existe " + e.toString(),2);
            }
        }
        return false;
    }
    
    public ResultSet hacerConsulta(String sql) {
        if (conexion != null) {
            HacerConsulta call = new HacerConsulta(conexion, sql);

            FutureTask<ResultSet> tarea = new FutureTask<ResultSet>(call);

            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.execute(tarea);
            try {
                while(!tarea.isDone())
                    cursorEspera(null);
                if(tarea.isDone()){
                   ResultSet valor = tarea.get();
                   cursorNormal(null);
                   executor.shutdown();
                   return valor;
                }
                cursorEspera(null);
                Thread.sleep(200);
            }catch(Exception e) {
                consola("HacerConsulta " + e.toString(),2);
            }
        }
        return null;
    }
    
    public int hacerConsulta2(String sql) {
        if (conexion != null) {
            HacerConsulta2 call = new HacerConsulta2(conexion, sql);

            FutureTask<Integer> tarea = new FutureTask<Integer>(call);

            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.execute(tarea);
            try {
                while(!tarea.isDone())
                    cursorEspera(null);
                if(tarea.isDone()){
                   Integer valor = tarea.get();
                   cursorNormal(null);
                   executor.shutdown();
                   return valor;
                }
            }catch(Exception e) {
                consola("HacerConsulta " + e.toString(),2);
            }
            
        }
        return -1;
    }
    
    public int aiConsulta(String sql, String [] datos, int numString, int numFloat) {
        if (conexion !=  null) {
            AIConsulta call = new AIConsulta(conexion, sql,datos, numString, numFloat);

            FutureTask<Integer> tarea = new FutureTask<Integer>(call);

            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.execute(tarea);
            try {
                while (!tarea.isDone()) {
                   cursorEspera(null);
                }
                if(tarea.isDone()){
                   Integer valor = tarea.get();
                   cursorNormal(null);
                   executor.shutdown();
                   consola("ConsultaDB.AIConsulta " + valor,0);
                   return valor;
                }
                    
            }catch(Exception e) {
                consola("ConsultaDB.AIConsulta " + e.toString(),2);
                return -1;
            }
            consola("ConsultaDB.AIConsulta salgo sin terminar la tarea",0);
        }
        return -1;
    }
    
    
    public void iniciarTiempo() {
       try {
            Tiempo call = new Tiempo(5000);

            FutureTask<String> tarea = new FutureTask<String>(call);

            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.execute(tarea);
            while (true) {

                    if(tarea.isDone()){
                       tarea.get();
                       cursorNormal(null);
                       executor.shutdown();
                       return;
                    }
                    cursorEspera(null);
            }
         }catch(Exception e) {
            consola("IniciarTiempo " + e.toString(),2);
        }
    }
}
